/****************
 *@description: 
 *@author: Xhd
 *@API: 
 *@date: 2023-12-07 10:07:17
 *@version: V1.0.0
*************************************************************************/

import React, { useState, useEffect, useRef } from "react";
import { Button, Modal, Steps, Row, Col, Space, message } from "antd";
import TheImage from "@/components/TheImage";
import TheButton from "@/components/TheButton";
import { Decimal } from 'decimal.js';
import { useNavigate, useLocation } from 'react-router-dom';
import { getOrderLogisticsDetail, expressageCompanySettingList } from '@/api/fundsManage/billList.js';
import { getDateTime2 } from '@/utils/getTimes'
import { ProForm, ModalForm, ProFormDateTimeRangePicker, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { apiSendOrders, apiShopOrderDetail, apiDeliverymanPage, apiReassignDeliveryman, apiEditCourierInformation } from "@/api/orderManage";

const { Step } = Steps;

const OrderTable = (props) => {
  const navigate = useNavigate();
  const formRef = useRef()
  const [logisticsModal, setLogisticsModal] = useState(false)
  const [courierCode, setCourierCode] = useState('')
  const [logisticsData, setLogisticsData] = useState([])
  const [courierNo, setCourierNo] = useState("")
  const [options, setOptions] = useState([])
  const [title, setTitle] = useState('')
  const [sendModal, setSendModal] = useState(false)
  const [mode, setMode] = useState("send")
  const [orderId, setOrderId] = useState("")
  const [off, setOff] = useState(1)
  const [courierOptions, setCourierOptions] = useState([])
  const orderType = ["普通订单", "砍价订单", "拼团订单", "奖品订单"]
  useEffect(() => {
    expressageCompanyData()
    getCourierOptions()
  }, [])
  //快递公司数据处理
  const expressageCompanyData = async () => {
    await expressageCompanySettingList().then(res => {
      if (res.code === 0 && res.data) {
        let data = res.data.map(v => {
          return {
            value: v.expressageCompanyCode,
            label: v.expressageCompanyName
          }
        })
        setOptions(data)
      }
    })
  }
  // 配送员列表
  let getCourierOptions = async () => {
    let res = await apiDeliverymanPage({ pageNo: 1, pageSize: -1 })
    if (res.code === 0 && res.data) {
      let courierOptions = []
      res.data.map(v => {
        if (v.hasBoundCar) {
          courierOptions.push({
            value: v.deliverymanId,
            label: v.name
          })
        }
      })
      setCourierOptions(courierOptions)
    }
  }

  let toOrderSalesDetail = (id) => {
    navigate('/orderManage/afterSaleOrder/detail', {
      state: {
        id
      }
    })
  }

  let toDetail = (id) => {
    navigate('/orderManage/mallOrder/detail', {
      state: {
        id
      }
    })
  }

  const logisticsDetail = async (shopOrderId) => {
    let hqmzps = ""
    let res = await apiShopOrderDetail({ orderId: shopOrderId })
    if (res.code === 0 && res.data.courierCode === "HQM") {
      hqmzps = "HQM"
    } else {
      hqmzps = ""
    }
    if (hqmzps === "HQM") {
      let context = null
      if (res.data.deliveryTask) {
        context = res.data.deliveryTask.hasOwnProperty('progressList') ? res.data.deliveryTask.progressList.map(v => {
          let time = v.createTime
          return {
            desc: v.progressDescription,
            time
          }
        }) : null
      }
      let courierCode = ""
      for (let i = 0; i < options.length; i++) {
        if (options[i].value === res.data.courierCode) {
          courierCode = options[i].label
        }
      }
      setLogisticsModal(true)
      setLogisticsData(context)
      setCourierCode(courierCode)
      setCourierNo(res.data.deliverymanName)
    } else {
      await getOrderLogisticsDetail(shopOrderId).then(res => {
        if (res.code === 0 && res.data) {
          let context = null
          if (res.data.msg) {
            context = res.data.msg.hasOwnProperty('context') ? res.data.msg.context.map(v => {
              let time = v.time * 1000
              time = new Date(parseInt(time))
              time = getDateTime2(time)
              return {
                ...v,
                time
              }
            }) : null
          }
          let courierCode = ""
          for (let i = 0; i < options.length; i++) {
            if (options[i].value === res.data.courierCode) {
              courierCode = options[i].label
            }
          }
          setLogisticsModal(true)
          setLogisticsData(context)
          setCourierCode(courierCode)
          setCourierNo(res.data.courierNo)
        }
      })
    }
  }

  const sendGoods = (id, type) => {
    if (type === "send") {
      setTitle("发货")
    } else {
      setTitle("修改快递")
      setMode(type)
    }
    setSendModal(true)
    setOrderId(id)
  }

  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  }
  return (
    <div>
      <table style={{ width: "100%", lineHeight: "40px", overflowX: "scroll" }}  >
        <thead style={{ textAlign: "center", backgroundColor: "#ddd" }}>
          <tr>
            <th colSpan={2}>商品</th>
            <th>单价（元）</th>
            <th>数量</th>
            <th>售后</th>
            <th>实付金额（元）</th>
            <th>订单状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr style={{ height: 10 }}></tr>
        </tbody>
        {props.dataSource.length !== 0 ? props.dataSource.map((v, i) => {
          let row = v.orderDetailList ? v.orderDetailList.length : 0
          let orderState = ""
          switch (v.orderState) {
            case "3":
              orderState = "待付款"
              break;
            case "4":
              orderState = "待发货"
              break;
            case "5":
              orderState = "待收货"
              break;
            case "6":
              orderState = "待分享"
              break;
            case "9":
              orderState = "交易成功"
              break;
            case "0":
              orderState = "交易关闭"
              break;
            default:
              break;
          }
          return <tbody key={i}>
            <tr style={{ backgroundColor: "#ddd" }}>
              <td colSpan={9} >
                <div style={{ display: "flex" }}>
                  <div>订单号：{v.orderCode}</div>
                  <div style={{ width: "40px" }}></div>
                  <div>下单时间：{v.createTime}</div>
                  <div style={{ width: "40px" }}></div>
                  {/* <div>{v.storeChannel === 1 ? <span style={{ backgroundColor: "red", borderRadius: "3px", color: "white", paddingLeft: "3px", paddingRight: "3px", marginRight: "5px" }}>自营</span> : null}{v.storeName}</div> */}
                  {/* <div style={{ width: "40px" }}></div> */}
                  <div>{orderType[v.activityTypeCode]}</div>
                </div>
              </td>
            </tr>
            {v.orderDetailList ? v.orderDetailList.map((item, index) => {
              let salesStatus = ""
              switch (item.salesStatus) {
                // case "1":
                //   salesStatus = "退款中"
                //   break;
                // case "2":
                //   salesStatus = "退款中，平台已同意，待寄回商品"
                //   break;
                // case "3":
                //   salesStatus = "退款中，商品已寄回，待平台确认"
                //   break;
                // case "4":
                //   salesStatus = "退款失败"
                //   break;
                // case "9":
                //   salesStatus = "退款成功"
                //   break;
                // case "0":
                //   salesStatus = "退款关闭"
                //   break;
                case "1": case "2": case "3":
                  salesStatus = "售后中"
                  break
                case "4": case "9": case "0":
                  salesStatus = "售后详情"
                  break
                default:
                  salesStatus = "-"
                  break;
              }
              let backgroundColor = salesStatus === "-" ? "" : "#F08080"
              if (index === 0) {
                return <tr style={{ textAlign: "center" }} key={index}>
                  <td width={100} style={{ paddingTop: "10px", backgroundColor }}><TheImage src={[item.goodsImage.split(',')[0]]} width={80} /></td>
                  <td width={300} style={{ backgroundColor }} >
                    <div className="goodsName" style={{
                      width: "30em",

                      textOverflow: "ellipsis", overflow: "hidden", whiteSpace: "nowrap",
                    }}>
                      {item.goodsName}
                    </div>
                    {item.goodsSkuJson ? JSON.parse(item.goodsSkuJson).hasOwnProperty("skuAttribute") ? JSON.parse(item.goodsSkuJson).skuAttribute.map((e) => {
                      return e.key + ":" + e.value
                    }) : JSON.parse(item.goodsSkuJson).key + ":" + JSON.parse(item.goodsSkuJson).value : null}
                  </td>
                  <td style={{ backgroundColor }}>{"￥" + Decimal(item.orderPrice).div(Decimal(100)).toNumber().toFixed(2)} </td>
                  <td style={{ backgroundColor }}>{"x" + item.orderGoodsCount}</td>
                  <td style={{ backgroundColor }}>{salesStatus === "-" ? salesStatus : <TheButton type="link" haspermi={['orderManage:list:afterSale']} onClick={() => toOrderSalesDetail(item.shopSalesReturnId)}>{salesStatus}</TheButton>}</td>
                  <td rowSpan={row}>{"￥" + Decimal(v.orderPayPrice).div(Decimal(100)).toNumber().toFixed(2)}<br />（含运费：{"￥" + Decimal(v.freight).div(Decimal(100)).toNumber().toFixed(2)} ）</td>
                  <td rowSpan={row}>{orderState}</td>
                  <td rowSpan={row}>
                    <TheButton type="link" haspermi={['orderManage:list:detail']} onClick={() => toDetail(v.shopOrderId)} >查看订单</TheButton>
                    {v.orderState === '4' ? <TheButton type="link" haspermi={['orderManage:list:send']} onClick={() => sendGoods(v.shopOrderId, "send")} >发货</TheButton> : null}
                    {v.orderState === '5' ? <TheButton type="link" haspermi={['orderManage:list:editSend']} onClick={() => sendGoods(v.shopOrderId, "edit")} >修改快递</TheButton> : null}
                    {["5", "9",].includes(v.orderState) ? <TheButton type="link" haspermi={['orderManage:list:checkLogistics']} onClick={() => logisticsDetail(v.shopOrderId)} >查看物流</TheButton> : null}
                  </td>
                </tr>
              }
              return <tr style={{ textAlign: "center" }} key={index}>
                <td width={100} style={{ paddingTop: "10px", backgroundColor }}><TheImage src={[item.goodsImage.split(',')[0]]} width={80} /></td>
                <td style={{ backgroundColor }}>
                  <div style={{ width: "30em", textOverflow: "ellipsis", overflow: "hidden", whiteSpace: "nowrap" }}>{item.goodsName}</div>
                  {JSON.parse(item.goodsSkuJson).skuAttribute.map((e) => {
                    return e.key + ":" + e.value
                  })}
                </td>
                <td style={{ backgroundColor }}>{"￥" + Decimal(item.orderPrice).div(Decimal(100)).toNumber().toFixed(2)}</td>
                <td style={{ backgroundColor }}>{"x" + item.orderGoodsCount}</td>
                <td style={{ backgroundColor }}>{salesStatus === "-" ? salesStatus : <TheButton type="link" haspermi={['orderManage:list:afterSale']} onClick={() => toOrderSalesDetail(item.shopSalesReturnId)}>{salesStatus}</TheButton>}</td>
              </tr>
            }) : <tr><td>订单数据异常</td></tr>}
          </tbody>
        })
          : <tbody>
            <tr><td colSpan={9} style={{ textAlign: "center", color: '#ddd' }}>暂无数据</td></tr>
          </tbody>
        }
      </table>
      <Modal
        title={"跟踪物流"}
        open={logisticsModal}
        onCancel={() => { setLogisticsModal(false) }}
        onOk={() => { setLogisticsModal(false) }}
        cancelButtonProps={{ style: { display: "none" } }}
      >
        <p>快递公司：{courierCode}</p>
        {courierCode === "哈奇马自配送" ?
          <p>配送员：{courierNo}</p>
          : <p>快递单号：{courierNo}</p>
        }
        {
          logisticsData ? <Steps progressDot current={0} direction="vertical">
            {logisticsData.map((v, i) => {
              return <Step title={v.time} description={v.desc} key={i} />
            })}
          </Steps> : <p>暂无物流信息</p>
        }
      </Modal>
      <ModalForm
        title={title}
        open={sendModal}
        {...formItemLayout}
        formRef={formRef}
        layout={'horizontal'}
        submitter={{
          render: (props, doms) => {
            return <Row>
              <Col span={22} offset={2}>
                <Space>{doms}</Space>
              </Col>
            </Row>
          },
        }}
        // onValuesChange={(changeValues) => console.log(changeValues)}
        onFinish={async (values) => {
          if (mode === "send") {
            await apiSendOrders({ ...values, orderId }).then((res) => {
              if (res.code === 0) {
                message.success('发货成功');
                setSendModal(false)
                props.getData()
              }
            })
          } else {
            if (off === 1) {
              await apiEditCourierInformation({ orderId, ...values }).then(res => {
                if (res.code === 0) {
                  message.success('提交成功');
                  setSendModal(false)
                  props.getData()
                }
              })
            } else {
              await apiReassignDeliveryman({ orderId, ...values }).then(res => {
                if (res.code === 0) {
                  message.success('提交成功');
                  setSendModal(false)
                  props.getData()
                }
              })
            }
          }
        }}
        modalProps={{
          destroyOnClose: true,
          width: 400,
          onCancel: () => setSendModal(false),
        }}
        onFinishFailed={(values) => {
          if (values.errorFields.length) {
            message.error('请完善数据')
          }
        }}
        params={{}}
        request={async () => {
          // await waitTime(100);
          // 判断当前页面类型
          if (mode === 'edit') {
            // 跑接口取回显数据
            let data
            let res = await apiShopOrderDetail({ orderId })
            if (res.code === 0 && res.data) {
              if (res.data.courierCode === "HQM") {
                setOff(2)
                data = {
                  courierCode: res.data.courierCode,
                  deliverymanId: res.data.deliveryTask.deliverymanId
                }
              } else {
                setOff(1)
                data = res.data
              }
              return data
            }
          } else {
            return {}
          }
        }}
      >
        <ProFormSelect
          width="md"
          name="courierCode"
          label="快递公司"
          options={options}
          rules={[{ required: true, message: '请选择快递公司' }]}
          onChange={(e) => {
            if (e === "HQM") {
              setOff(2)
            } else {
              setOff(1)
            }
          }}
        />
        {
          off === 1 ?
            <ProFormText
              width="md"
              name="courierNo"
              label="快递单号"
              rules={[{ required: true, message: '请输入快递单号' }]}
            />
            : <ProFormSelect
              width="md"
              name="deliverymanId"
              label="配送员"
              options={courierOptions}
              rules={[{ required: true, message: '请选择配送员' }]}
            />
        }
      </ModalForm>
    </div>
  )
}

export default OrderTable
